package cn.imokay.stopthread;

/**
 * run方法有sleep，如果执行过程中，每次循环都会sleep或者wait
 * 无需每次迭代都近行判断<code>!Thread.currentThread().isInterrupted()</code>
 * 因为sleep的时候会自动判断
 *
 *当try catch在循环中时，捕获异常后没有进行中断，即使增加了<code>!Thread.currentThread().isInterrupted()</code>判断，也无法中断，因为sleep时isInterrupted被重置了
 */
public class RightWayStopThreadWithSleepEveryLoop {


    public static void main(String[] args) throws InterruptedException {

        Runnable r = () -> {
            int num = 0;
            try {
                while ( num <= 10000) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的整数倍");
                    }
                    num++;
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                //sleep的过程中，如果收到终止通知，则会抛出异常用以中断线程，捕获异常后需要处理收到中断通知后的一些收尾工作
                e.printStackTrace();
            }
            System.out.println("finished");
        };
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }
}
